package com.sti.framework.models.User.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sti.framework.core.service.BaseService;
import com.sti.framework.core.web.Page;
import com.sti.framework.core.web.SimplePage;
import com.sti.framework.models.User.data.User;
import com.sti.framework.models.User.data.UserSearchWhere;
import com.sti.framework.models.User.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


/**
 * 模块： 包括角色、权限等管理功能
 * 表　： 用户信息
 *
 * @author AutoApi
 */
@Service
public class UserService extends BaseService<UserMapper, User> {

    public SimplePage<User> getAll(Page page, UserSearchWhere searchWhere) {

        //查询条件
        QueryWrapper<User> wrapper = Page.getQueryWrapper(searchWhere);

        // 不显示超级管理员
        wrapper.ne("role_id",23691354597501L);

        IPage<User> list = super.getBaseMapper().selectPage(page, wrapper);
        return new SimplePage(list.getRecords(), list.getTotal(),list.getCurrent(),list.getSize());
    }

    public User get(String username, String password) {

        //查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 不显示超级管理员
        wrapper.eq("username",username);
        wrapper.eq("password",password);

        return super.getOne(wrapper);
    }

    @Override
    @Transactional(value = "transactionManager")
    public void create(User user) {
        if (user.getPassword() != null){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        super.create(user);
    }

    @Override
    @Transactional(value = "transactionManager")
    public void update(User user) {
        User ouser = super.get(user.getId());
        //必须要在执行修改密码情况下进行将密码再次加密
        if (StringUtils.isNotEmpty(user.getPassword()) && StringUtils.isNotEmpty(user.getIsEncipherFlag())){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        String[] nullProperties = getNullProperties(user);
        BeanUtils.copyProperties(user, ouser, nullProperties);

        super.updateById(ouser);
    }
}
